<template>
  <!-- 停机类型表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    style="min-width: 600px; max-width: 800px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工厂" prop="plantId" required>
            <el-select
              v-if="!props.isReadonly"
              @change="plantChange"
              v-model="formData.plantId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in plants"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else> {{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="呼叫类型" prop="callTypeId" required>
            <el-select
              v-if="!props.isReadonly"
              @change="andcalltypesChange"
              v-model="formData.callTypeId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in andcalltypes"
                :key="item.id"
                :label="item.callTypeName"
                :value="item.id"
              />
            </el-select>
            <span v-else> {{ formData.callTypeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="停机类型编码" prop="stopTypeCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.stopTypeCode"
              placeholder="请输入停机类型编码"
              clearable
              style="width: 200px"
            />

            <span v-else>{{ formData.stopTypeCode }}</span>
          </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item label="停机类型名称" prop="stopTypeName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.stopTypeName"
              placeholder="请输入停机类型名称"
              clearable
              style="width: 200px"
            />

            <span v-else>{{ formData.stopTypeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item label="停机类型分组" prop="stopTypeGroup">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.stopTypeGroup"
              placeholder="请输入停机类型分组"
              clearable
              style="width: 200px"
            />
            <span v-else>{{ formData.stopTypeGroup }}</span>
          </el-form-item></el-col
        >
        <el-col :span="12">
          <el-form-item label="安东操作" prop="operateSetting" required>
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.operateSetting"
              placeholder="请选择安东操作"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'AndonCallSetting'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              useDictionary("AndonCallSetting", formData.operateSetting)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="12">
        <el-form-item label="是否启用" prop="enabled">
          <template v-if="!props.isReadonly">
            <el-radio-group v-model="formData.enabled">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </template>
          <span v-else>{{
            dictionaryStore.filterDictName("YesNo", formData.enabled)
          }}</span>
        </el-form-item>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item
            v-if="props.isReadonly !== false"
            label="创建时间"
            prop="createTime"
          >
            <span>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12"
          ><el-form-item
            v-if="props.isReadonly !== false"
            label="创建人"
            prop="createdUserName"
          >
            <span>{{ formData.createdUserName }}</span>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            v-if="props.isReadonly !== false"
            label="修改时间"
            prop="lastUpdateTime"
          >
            <span>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="props.isReadonly !== false"
            label="修改人"
            prop="lastUpdatedUserName"
          >
            <span>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item></el-col
        >
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useDictionary } from "@/utils/useTable";
defineOptions({
  name: "ANDONANDSTOPTYPEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let plants = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getPlants();
    if (newVal === true) {
      setTimeout(() => {
        formRef.value.clearValidate();
      }, 50);
    }
  }
);

const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "blur" }],
  callTypeId: [{ required: true, message: "请选呼叫类型", trigger: "blur" }],
  plantCode: [
    { required: true, message: "请选择工厂", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  stopTypeCode: [
    { required: true, message: "请输入停机类型编码", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  stopTypeName: [
    { required: true, message: "请输入停机类型名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  stopTypeGroup: [
    { required: true, message: "请输入停机类型分组", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  callTypeId: "",
  callTypeCode: "",
  callTypeName: "",
  plantCode: "",
  stopTypeCode: "",
  stopTypeName: "",
  stopTypeGroup: "",
  operateSetting: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        organizationCode,
        plantId,
        callTypeId,
        callTypeCode,
        callTypeName,
        plantCode,
        stopTypeCode,
        stopTypeName,
        stopTypeGroup,
        operateSetting,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        organizationCode,
        plantId,
        callTypeId,
        callTypeCode,
        callTypeName,
        plantCode,
        stopTypeCode,
        stopTypeName,
        stopTypeGroup,
        operateSetting,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.callTypeId = "";
  formData.callTypeCode = "";
  formData.callTypeName = "";
  formData.stopTypeCode = "";
  formData.stopTypeName = "";
  formData.stopTypeGroup = "";
  formData.operateSetting = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}

const loading = ref(false);
async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
  if (formData.plantId) {
    getandcalltypes(formData.plantId);
  }
}
function plantChange() {
  var plant = plants.value.find((item) => {
    return item.id === formData.plantId;
  });
  formData.plantCode = plant.organizationCode;
  getandcalltypes(formData.plantId);
}
/** 停机类型保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/andon/andstoptype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

let andcalltypes = ref([]);
//获取呼叫类型
async function getandcalltypes(id: string) {
  const data = await request({
    url: "/andon/andcalltype/getCallTypes",
    method: "post",
    data: {
      plantId: id,
    },
  });
  andcalltypes.value = data.data;
}

function andcalltypesChange() {
  var andcalltype = andcalltypes.value.find((item) => {
    return item.id === formData.callTypeId;
  });
  formData.callTypeCode = andcalltype.callTypeCode;
}
</script>
